Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is >not good in maths. Can you help him to find out, how many cakes he could bake >considering his recipes?
Write a function cakes(), which takes the recipe (object) and the available ingredients >(also an object) and returns the maximum number of cakes Pete can bake (integer). For >simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are >simply 1 or 200). Ingredients that are not present in the objects, can be considered as >0.
Examples:
#must return 2
cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: >200})
#must return 0
cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: >2000, milk: 2000})
題目理解:編寫一個函式接受兩參數,食譜recipe&可用食材available。兩者皆為字典形式,其key為食材成分,並有對應的值。根據食譜recipe所表達製作一份的需求量,來計算可用食材available能製作多少份並返還數量。
def cakes(recipe, available):
lst = []
#檢驗每項recipe中食材是否有出現在available中
for ing in recipe.keys():
#若available缺少食譜中食材則直接返還0
if ing not in available.keys():
return 0
#將可用食材的數量/食譜指定數量,用int()取整即為單品項成分可製作的份數並存入lst
lst.append(int(available[ing]/recipe[ing]))
return min(lst)